/**
 * @BitmapNum.as
 *
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2014 ASFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:Battle
 * <br>Date:2014-5-14
 */
package com.asframe.display.nums
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;

	/**
	 * 图片组合成的数字
	 * @author sodaChen
	 * Date:2014-5-14
	 */
	public class BitmapNums extends Sprite
	{
		/** 左边对齐 **/
		public static const LEFT_MODE:int = 1;
		/** 中间对齐 **/
		public static const MID_MODE:int = 2;
		/** 右边对齐 **/
		public static const RIGHT_MODE:int = 3;

		/** 自己计算宽时的x偏移值，默认是5**/
		public var numOffsetX:int = 5;
		private var bitmapDatas:Vector.<BitmapData>;
		private var bitmaps:Vector.<Bitmap>;
		private var maxLen:int;
		private var align:int;
		private var isShowZero:Boolean;
		private var _showWidth:Number;
		private var fixedWidth:int;

		public function BitmapNums(bitmapDatas:Vector.<BitmapData> = null,maxLen:int = 10,isShowZero:Boolean = false)
		{
			if(bitmapDatas != null)
				initNums(bitmapDatas,maxLen,isShowZero);
		}

		/**
		 * 初始化数组，里面是0到9的顺序排放的BitmapData对象
		 * @param bitmapDatas
		 * @param maxLen 数字最大长度，默认是10，为最长
		 * @param isShowZero 是否显示前面的0
		 *
		 */
		public function initNums(bitmapDatas:Vector.<BitmapData>,maxLen:int = 10,isShowZero:Boolean = false):void
		{
			this.bitmapDatas = bitmapDatas;
			this.align = align;
			this.maxLen = maxLen;
			this.isShowZero = isShowZero;
			bitmaps = new Vector.<Bitmap>();
			for(var i:int = 0;i < maxLen;i++)
			{
				bitmaps.push(new Bitmap());
			}
		}

		public function get showWidth():Number
		{
			return _showWidth;
		}

		public function set showWidth(value:Number):void
		{
			_showWidth = value;
		}
		/**
		 * 设置数字的固定宽度(不依赖每个数字的宽度)
		 * @param fixedWidth
		 *
		 */
		public function fixedNumWidth(fixedWidth:int,align:int = 0):void
		{
			this.fixedWidth = fixedWidth;
		}
		public function clearNums():void
		{
			for (var i:int = 0; i < bitmaps.length; i++)
			{
				if(bitmaps[i] != null && bitmaps[i].parent == this)
					removeChild(bitmaps[i]);
			}
		}
		public function showNums(num:Number):void
		{
			clearNums();
			//转换成单个
			var numList:Array = num.toString().split("");
			var len:int = numList.length;
			if(isShowZero && len < maxLen)
			{
				var cha:int = maxLen - len;
				for (var j:int = 0; j < cha; j++)
				{
					numList.unshift("0");
				}
				len = numList.length;
			}
			var bitmap:Bitmap = null;
			var allWidth:int = 0;
			//实时计算每个数字的宽(左边的时候用)
			var width:int;
			for (var i:int = 0; i < len; i++)
			{
				bitmap = bitmaps[i];
				bitmap.bitmapData = bitmapDatas[int(numList[i])];
				if(fixedWidth != 0)
				{
					//位图自己的位置
					bitmap.x = allWidth + (fixedWidth - bitmap.width) / 2
					//等宽
					allWidth += fixedWidth;
				}
				else
				{
					bitmap.x = allWidth;
					//自动根据图像的宽来计算(数组中心来计算)
					allWidth += bitmap.width - numOffsetX;
				}
				//按照顺序排好
				addChild(bitmap);
			}
		}
	}
}